package com.yhp.servlet;

import com.yhp.bean.Student;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/Educational/student/editsave")
public class EditSaveServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService studentService = new StudentServiceImpl();
        //接收参数
        String stuid = req.getParameter("stuid");
        String stuno = req.getParameter("stuno");
        String stuname = req.getParameter("stuname");
        String gradeid = req.getParameter("gradeid");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String registered = req.getParameter("registered");
        String address = req.getParameter("address");
        String politics = req.getParameter("politics");
        String idNumber = req.getParameter("idNumber");
        String profession = req.getParameter("profession");
        String intro = req.getParameter("intro");
        Student student = new Student(Integer.parseInt(stuid), stuname, stuno, Integer.parseInt(sex),
                phone, email, registered, address, profession, idNumber, politics, intro, Integer.parseInt(gradeid));
        //更新数据
        //判断学号是否重复
        String isrepeat = studentService.isrepeat(stuno);
        String prestuno = req.getParameter("prestuno");
        System.out.println("查询的数据:"+isrepeat);
        System.out.println("原有的数据:"+prestuno);
        System.out.println("两者比较prestuno.equals(isrepeat):"+prestuno.equals(isrepeat));
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //if(isrepeat == null || )
        if(isrepeat != null && !prestuno.equals(isrepeat)){
            //重复
            writer.println("<script>alert('学号已存在，请重新输入！');location.href='/Educational/student/myedit?stuid="+stuid+"';</script>");
        }else {

            int update = studentService.update(student);
            //判断是否更新成功
            if(update > 0){
                writer.println("<script>alert('更新成功');location.href='/Educational/student/getList';</script>");
            }else {
                writer.println("<script>alert('更新失败');location.href='/Educational/student/myedit?stuid="+stuid+"';</script>");
            }
        }
    }
}
